package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.enums.AuditStatusEnum;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.AgencyCertificationAuditMapper;
import com.jzo2o.customer.model.domain.AgencyCertification;
import com.jzo2o.customer.model.domain.AgencyCertificationAudit;
import com.jzo2o.customer.model.domain.ServeProvider;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.AgencyCertificationAuditPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.CertificationAuditReqDTO;
import com.jzo2o.customer.model.dto.response.AgencyCertificationAuditResDTO;
import com.jzo2o.customer.model.dto.response.RejectReasonResDTO;
import com.jzo2o.customer.service.IAgencyCertificationAuditService;
import com.jzo2o.customer.service.IAgencyCertificationService;
import com.jzo2o.customer.service.IServeProviderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description AgencyCertificationAuditServiceImpl
 * @Author jzh
 * @Date 2025-08-07  14:32
 */
@Service
public class AgencyCertificationAuditServiceImpl extends ServiceImpl<AgencyCertificationAuditMapper, AgencyCertificationAudit> implements IAgencyCertificationAuditService {

    @Resource
    private IAgencyCertificationService agencyCertificationService;

    @Resource
    private IServeProviderService serveProviderService;

    @Override
    @Transactional
    public void auditSubmit(AgencyCertificationAuditAddReqDTO agencyCertificationAuditAddReqDTO) {
        // 新增认证审核记录
        AgencyCertificationAudit agencyCertificationAudit = BeanUtil.toBean(agencyCertificationAuditAddReqDTO, AgencyCertificationAudit.class);
        // 默认未审核
        agencyCertificationAudit.setAuditStatus(AuditStatusEnum.NO.getStatus());
        save(agencyCertificationAudit);

        // 查询认证记录
        Long serveProviderId = agencyCertificationAudit.getServeProviderId();
        // 同步写入service_provider表中name字段
        ServeProvider serveProvider = serveProviderService.getById(serveProviderId);
        serveProvider.setName(agencyCertificationAuditAddReqDTO.getName());
        serveProviderService.updateById(serveProvider);

        AgencyCertification agencyCertification = agencyCertificationService.getById(serveProviderId);
        if(ObjectUtil.isNotNull(agencyCertification)){
            // 将认证状态更新为认证中
            agencyCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
            agencyCertificationService.updateById(agencyCertification);
        } else {
            agencyCertification = new AgencyCertification();
            agencyCertification.setId(serveProviderId);
            agencyCertification.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
            agencyCertificationService.save(agencyCertification);
        }
    }

    /**
     * 审核服务机构认证分页查询
     * @param agencyCertificationAuditPageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<AgencyCertificationAuditResDTO> pageQueryAgencyAudit(AgencyCertificationAuditPageQueryReqDTO agencyCertificationAuditPageQueryReqDTO) {
        PageHelper.startPage(Math.toIntExact(agencyCertificationAuditPageQueryReqDTO.getPageNo()), Math.toIntExact(agencyCertificationAuditPageQueryReqDTO.getPageSize()));
        Page<AgencyCertificationAuditResDTO> page = baseMapper.pageQueryAgencyAudit(agencyCertificationAuditPageQueryReqDTO);

        PageResult<AgencyCertificationAuditResDTO> result = new PageResult<>();
        result.setPages((long) page.getPages());
        result.setList(page.getResult());
        result.setTotal(page.getTotal());
        return result;
    }

    /**
     * 审核服务机构认证
     * @param id
     * @param certificationAuditReqDTO
     */
    @Override
    public void audit(Long id, CertificationAuditReqDTO certificationAuditReqDTO) {
        // 查询认证记录
        AgencyCertificationAudit agencyCertificationAudit = getById(id);
        if (ObjectUtil.isNull(agencyCertificationAudit)){
            throw new ForbiddenOperationException("认证记录不存在");
        }

        Integer auditStatus = agencyCertificationAudit.getAuditStatus();
        if (auditStatus == AuditStatusEnum.YES.getStatus()){
            throw new ForbiddenOperationException("认证记录已审核");
        }

        agencyCertificationAudit.setAuditStatus(AuditStatusEnum.YES.getStatus());
        agencyCertificationAudit.setCertificationStatus(certificationAuditReqDTO.getCertificationStatus());
        agencyCertificationAudit.setAuditorId(UserContext.getCurrentUser().getId());
        agencyCertificationAudit.setAuditorName(UserContext.getCurrentUser().getName());
        agencyCertificationAudit.setAuditTime(LocalDateTime.now());

        // 如果认证成功，同步写入认证信息agency_certification表
        if (certificationAuditReqDTO.getCertificationStatus() == CertificationStatusEnum.FAIL.getStatus()){
            // 填充拒绝原因
            String rejectReason = certificationAuditReqDTO.getRejectReason();
            agencyCertificationAudit.setRejectReason(rejectReason);

            AgencyCertification agencyCertification = new AgencyCertification();
            agencyCertification.setCertificationStatus(CertificationStatusEnum.FAIL.getStatus());
            agencyCertification.setCertificationTime(LocalDateTime.now());
            agencyCertification.setId(agencyCertificationAudit.getServeProviderId());
            agencyCertificationService.updateById(agencyCertification);
        }
        updateById(agencyCertificationAudit);

        // 如果认证成功，同步写入认证信息worker_certification表
        if (certificationAuditReqDTO.getCertificationStatus() == CertificationStatusEnum.SUCCESS.getStatus()){
            AgencyCertification agencyCertification = new AgencyCertification();
            agencyCertification.setId(agencyCertificationAudit.getServeProviderId());
            agencyCertification.setName(agencyCertificationAudit.getName());
            agencyCertification.setIdNumber(agencyCertificationAudit.getIdNumber());
            agencyCertification.setLegalPersonName(agencyCertificationAudit.getLegalPersonName());
            agencyCertification.setLegalPersonIdCardNo(agencyCertificationAudit.getLegalPersonIdCardNo());
            agencyCertification.setBusinessLicense(agencyCertificationAudit.getBusinessLicense());
            agencyCertification.setCertificationTime(agencyCertificationAudit.getAuditTime());
            agencyCertification.setCertificationStatus(CertificationStatusEnum.SUCCESS.getStatus());
            agencyCertificationService.updateById(agencyCertification);
        }
    }

    /**
     * 查询最新的驳回原因
     * @return
     */
    @Override
    public RejectReasonResDTO rejectReason() {
        Long serveProviderId = UserContext.getCurrentUser().getId();

        List<AgencyCertificationAudit> agencyCertificationAuditList = lambdaQuery()
                .eq(AgencyCertificationAudit::getServeProviderId, serveProviderId)
                .eq(AgencyCertificationAudit::getAuditStatus, AuditStatusEnum.YES.getStatus())
                .orderByDesc(AgencyCertificationAudit::getCreateTime)
                .list();

        if (ObjectUtil.isNull(agencyCertificationAuditList)){
            throw new ForbiddenOperationException("还未审核");
        }
        // 取workerCertificationAuditList中最新的认证记录
        AgencyCertificationAudit agencyCertificationAudit = agencyCertificationAuditList.get(0);
        String rejectReason = agencyCertificationAudit.getRejectReason();

        RejectReasonResDTO rejectReasonResDTO = new RejectReasonResDTO(rejectReason);
        return rejectReasonResDTO;
    }
}
